package com.nbsaas.boot.script.ext.resource;

import com.nbsaas.boot.script.ext.apis.ScriptResource;
import com.nbsaas.boot.script.ext.domain.simple.ScriptSource;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * 文件系统脚本源
 */
public class FileScriptSource implements ScriptResource {

    @Override
    public String getPrefix() {
        return "file:";
    }

    @Override
    public ScriptSource loadScript(String path) {
        String actual = path.startsWith(getPrefix()) ? path.substring(getPrefix().length()) : path;
        File file = new File(actual);
        if (!file.exists()) {
            return null;
        }
        ScriptSource result = new ScriptSource();
        try {
            result.setScript(Files.readString(file.toPath(), StandardCharsets.UTF_8));
            result.setTimestamp(file.lastModified());
            return result;
        } catch (Exception ignored) {
        }
        return null;
    }
}
